package com.asen.commons.core.jdbc.builder.mysql.filter;

import com.asen.commons.core.jdbc.param.SqlColumn;
import com.asen.commons.core.jdbc.param.SqlContextManager;
import com.asen.commons.core.meta.dao.FilterItem;
import com.asen.commons.utils.BaseAssert;
import com.asen.commons.utils.StringUtils;

/**
 * Custom过滤解析器
 *
 * @author Gary
 * @version 1.0
 * @date 2021-08-22
 */
public class CustomFilterParser implements FilterParser {

    @Override
    public CharSequence parse(SqlContextManager contextManager, FilterItem filterItem) {
        Object value = filterItem.getValue();
        if (value == null) {
            return null;
        }

        String result = parseCustom(contextManager, value.toString());
        return StringUtils.isBlank(result) ? result : "(" + result + ")";
    }

    private String parseCustom(SqlContextManager contextManager, String sql) {
        if (StringUtils.isEmpty(sql)) {
            return "";
        }

        int beginIndex = sql.indexOf("${");
        if (beginIndex == -1) {
            return sql;
        }

        StringBuilder result = new StringBuilder();
        result.append(sql.substring(0, beginIndex));
        int endIndex = sql.indexOf("}");
        String fieldName = sql.substring(beginIndex + 2, endIndex);
        SqlColumn sqlColumn = contextManager.getSqlColumn(fieldName);
        BaseAssert.notNull(sqlColumn, "属性变量字段${" + fieldName + "}不存在！");
        result.append(sqlColumn.getFullColumn());
        result.append(parseCustom(contextManager, sql.substring(endIndex + 1)));
        return result.toString();
    }

}
